package com.ppt.javappt.controller;

import com.ppt.javappt.HelloApplication;
import com.ppt.javappt.em.IconPathEnum;
import com.ppt.javappt.entity.Slide;
import com.ppt.javappt.entity.SlideFile;
import com.ppt.javappt.component.TextBox;
import com.ppt.javappt.util.SystemUtil;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Side;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Rectangle;

import java.util.Iterator;

import static com.ppt.javappt.util.SystemUtil.isDescendant;

/**
 * @author cys
 */
public class HelloController {
    SystemUtil sys = SystemUtil.getInstance();
    public static Slide curSlide;
    public static Node focusComponent;
    @FXML
    AnchorPane anchorPane;
    @FXML
    AnchorPane textSetting;
    @FXML
    TabPane menu;
    @FXML
    Tab fileTab;
    @FXML
    Tab beginTab;
    @FXML
    Tab insertTab;
    @FXML
    Button pictureBtn;

    @FXML
    Button textBoxBtn;
    @FXML
    ComboBox<String> textFamilySelect;
    @FXML
    ComboBox<String> textSizeSelect;
    @FXML
    ToggleButton textBoldToggle;
    @FXML
    ToggleButton textItalicToggle;
    @FXML
    ToggleButton textUnderlineToggle;
    @FXML
    Button textColorButton;
    @FXML
    ContextMenu textColorMenu;
    @FXML
    Button whiteBtn;
    @FXML
    Button blackBtn;
    @FXML
    Button redBtn;
    @FXML
    Button orangeBtn;
    @FXML
    Button yellowBtn;
    @FXML
    Button greenBtn;
    @FXML
    Button aquaBtn;
    @FXML
    Button blueBtn;
    @FXML
    Button purpleBtn;

    @FXML
    Button newFileBtn;
    @FXML
    Button newSlideBtn;
    @FXML
    Button newRectBtn;
    @FXML
    Button saveFileBtn;
    @FXML
    Button openFileBtn;
    @FXML
    Button outputBtn;
    @FXML
    Button delSlideBtn;
    @FXML
    Button outputSlideBtn;

    ImageView pictureIcon = new ImageView(new Image(IconPathEnum.INSERT_PICTURE.getUrl()));
    ImageView newFileIcon = new ImageView(new Image(IconPathEnum.NEW_FILE.getUrl()));
    ImageView saveFileIcon = new ImageView(new Image(IconPathEnum.SAVE_FILE.getUrl()));
    ImageView openFileIcon = new ImageView(new Image(IconPathEnum.OPEN_FILE.getUrl()));

    // 切换菜单栏部分
    // 文件 File
    @FXML
    public void fileFun(){
        newFileIcon.setFitHeight(32);
        newFileIcon.setFitWidth(32);
        openFileIcon.setFitHeight(32);
        openFileIcon.setFitWidth(32);
        saveFileIcon.setFitHeight(32);
        saveFileIcon.setFitWidth(32);

        newFileBtn.setGraphic(newFileIcon);
        openFileBtn.setGraphic(openFileIcon);
        saveFileBtn.setGraphic(saveFileIcon);
    }
    // 开始 Begin
    @FXML
    public void beginFun(){
        SlideFile curSlideFile = sys.getCurSlideFile();
        if(curSlideFile == null){
            return;
        }
        if (!anchorPane.getChildren().contains(curSlideFile)) {
            anchorPane.getChildren().add(curSlideFile);
            AnchorPane.setTopAnchor(curSlideFile, 100.0);
        }
    }
    // 插入 Insert
    @FXML
    public void insertFun(){
        pictureIcon.setFitHeight(32);
        pictureIcon.setFitWidth(32);
        pictureBtn.setGraphic(pictureIcon);
    }
    // 第一个功能 新建一个新的文件 SlideFile
    // 自动切换到 beginTab
    public void newFile(){
        if(sys.getCurSlideFile()!=null){
            sys.getCurSlideFile().clear();
        }else{
            sys.setCurSlideFile(new SlideFile());
        }
        Platform.runLater(()->{
            menu.getSelectionModel().select(beginTab);
        });
    }
    // 第二个功能
    // 创建新的幻灯片页 并展现在界面上

    @FXML
    public void createSlide(){
        SlideFile curSlideFile = sys.getCurSlideFile();
        if (curSlideFile == null) {
            return; // 空指针防护：无当前文件时不执行
        }
        curSlide = new Slide();
        curSlide.toFront();
        listenSlideFocus();
        curSlideFile.getSlideList().add(curSlide);
        sys.getSlideStackPane().setSlideList(sys.getCurSlideFile().getSlideList());
        sys.getThumbnailPane().setSlideList(sys.getCurSlideFile().getSlideList());

        curSlide.addEventFilter(MouseEvent.MOUSE_MOVED, event -> {
            System.out.println("x:" + event.getX() + " y:" + event.getY());
        });
    }
    // 三个功能 DemoTest
    // 新建矩形

    public void createRect(){
        if(curSlide!=null){
            Rectangle rect = new Rectangle(200,100);
            rect.setX(50);
            rect.setY(50);
            curSlide.getChildren().add(rect);
        }
    }



    // 新建文本框
    public void createTextBox() {
        if(curSlide!=null){
            curSlide.setCursor(Cursor.CROSSHAIR);
            curSlide.setOnMousePressed(event -> {
                TextBox tb;
                double x = event.getX();
                double y = event.getY();
                // 移除按下监听
                curSlide.setOnMousePressed(null);

                // 放置文本框
                curSlide.getChildren().add(tb = new TextBox(x, y));
                // 放置后监听鼠标拖拽（移动）
                curSlide.setOnMouseDragged(e -> {
                    tb.setPrefSize(Math.abs(e.getX() - x), Math.abs(e.getY() - y));
                });
                // 监听鼠标释放
                curSlide.setOnMouseReleased(e -> {
                    curSlide.setCursor(HelloApplication.cursor);
                    curSlide.setOnMouseDragged(null);
                    curSlide.setOnMouseReleased(null);
                });
            });
        }
        menu.getSelectionModel().select(beginTab);
    }


    // 保存文件
    public void saveFile(){
        sys.getCurSlideFile().saveFile();
    }
    // 打开文件
    public void openFile(){
        if(sys.getCurSlideFile()!=null){
            sys.getCurSlideFile().loadFile();
        }else{
            sys.setCurSlideFile(new SlideFile());
            sys.getCurSlideFile().loadFile();
        }
//        Platform.runLater(()->{
//            update();
//            menu.getSelectionModel().select(beginTab);
//        });
        Platform.runLater(()->{
            update();
        });
        menu.getSelectionModel().select(beginTab);
    }
    // 删除某一页幻灯片
    public void delSlide(){
        sys.getCurSlideFile().delSlide();
    }
    // 另存为（JavaPPT / pdf）
    public void outputFile(){
        sys.getCurSlideFile().saveAsFile();
    }
    // 导出某一页幻灯片
    public void outputSlide(){
        sys.getCurSlideFile().outputSlide();
    }
    @FXML
    public void initialize(){
        fileFun();
    }
    // TODO 当前做一个补丁
    // TODO 直接读取文件中 文本框在缩略图未显示
    public void update(){
        sys.getCurSlideFile().updateThumbnailPane();
    }
    // 获取幻灯片内焦点
    public void listenSlideFocus(){
        if (curSlide == null) {return;}
        curSlide.addEventFilter(MouseEvent.MOUSE_RELEASED, event -> {
            if (isDescendant(curSlide, HelloApplication.focus)) {
                System.out.println("focus: " + HelloApplication.focus.getTypeSelector());
                focusComponent = HelloApplication.focus;

                switch (focusComponent.getTypeSelector()){
                    case "TextBox": updateTextSetting(); break;
                    default: break;
                }
            }
            else {
                //clearTextSetting();
            }
        });
    }

    //
    public void textColorMenuInit(){

    }

    // 根据选中文本框更新字体设置栏
    public void updateTextSetting(){
        TextBox tb = ((TextBox)focusComponent);
        textBoldToggle.setSelected(tb.isBold());
        textItalicToggle.setSelected(tb.isItalic());
        textFamilySelect.getSelectionModel().select(tb.getFontFamily());
        textSizeSelect.getSelectionModel().select(Integer.toString(tb.getFontSize()));
    }

    // 清除样式字体设置栏状态
    public void clearTextSetting(){
        textBoldToggle.setSelected(false);
        textItalicToggle.setSelected(false);
        textSizeSelect.getSelectionModel().clearSelection();
    }

    public void toggleBold() {
        ((TextBox)focusComponent).toggleBold();
    }

    public void toggleItalic() {
        ((TextBox)focusComponent).toggleItalic();
    }

    public void changeTextFamily() {
        ((TextBox)focusComponent).setFontFamily(
                textFamilySelect.getSelectionModel().getSelectedItem().toString()
        );
    }


    public void changeTextSize(){
        ((TextBox)focusComponent).setFontSize(
                Integer.parseInt(textSizeSelect.getSelectionModel().getSelectedItem().toString())
        );
    }
    public void toggleUnderline() {
        ((TextBox)focusComponent).toggleUnderline();
    }

    public void changeTextColor(ActionEvent event) {
        String id = ((Button)event.getSource()).getId();
        switch (id){
            case "whiteBtn": ((TextBox)focusComponent).setColor("white"); break;
            case "blackBtn": ((TextBox)focusComponent).setColor("black"); break;
            case "redBtn": ((TextBox)focusComponent).setColor("red"); break;
            case "orangeBtn": ((TextBox)focusComponent).setColor("orange"); break;
            case "yellowBtn": ((TextBox)focusComponent).setColor("yellow"); break;
            case "greenBtn": ((TextBox)focusComponent).setColor("green"); break;
            case "aquaBtn": ((TextBox)focusComponent).setColor("aqua"); break;
            case "blueBtn": ((TextBox)focusComponent).setColor("blue"); break;
            case "purpleBtn": ((TextBox)focusComponent).setColor("purple"); break;
            default: break;
        }
    }

    public void showTextColorMenu() {
        textColorMenu.show(textColorButton, Side.BOTTOM, 0, 0);
    }


}